var wsUrl = "127.0.0.1:10106/ws/screen/test";
var websocket = null;
var autoReconnect = true;
var urlArray = ["http://127.0.0.1:2080/2021/page1/index.html","http://127.0.0.1:2080/2021/page1/index.html?theme=234"];
var currentUrlIndex = 0;
var reloadTimer;
var timeArray = ['01:57:00','12:30:00','06:00:00']
chrome.runtime.onInstalled.addListener(({reason}) => {
    console.log("websocket")
    createWebSocketConnection()
    // if (reason === 'install') {
    //     console.log('extension installed')
    //     createWebSocketConnection()
    // }
    //指定时间重启页面
    if(!reloadTimer)
    {
        console.log('create reloadTimer')
        reloadTimer = setInterval(() => {
            timeArray.forEach(ele => {
                let currentTime = new Date();
                let targetTime = new Date();
                let timeStrs = ele.split(':')
                targetTime.setHours(timeStrs[0])
                targetTime.setMinutes(timeStrs[1])
                targetTime.setSeconds(timeStrs[2])
                let timeGap = currentTime.getTime() - targetTime.getTime()
                if(timeGap > 0 && timeGap < 360000) //当前时间与定时器时间相差6分钟以内时，重启页面
                {
                    urlArray.forEach(originUrl => {
                        chrome.tabs.query({},function(tabs){
                            tabs.forEach(tab => {
                                if(tab.url == originUrl)
                                {
                                    console.log('reload tab:',tab)
                                    chrome.tabs.reload(tab.id)
                                }
                            });
                        })
                    });
                }
            });
        }, 5* 60 * 1000);//five minitues cycle
    }
});

function createWebSocketConnection() {
    if('WebSocket' in window){
        // chrome.storage.local.get("instance", function(data) {
        //     connect('ws://' +wsUrl);
        // });
        connect('ws://' + wsUrl)
    }
}

//Make a websocket connection with the server.
function connect(host) {
    if (undefined === websocket || null === websocket) {
        console.log('websocket connect to host' + host)
        websocket = new WebSocket(host);
    }

    websocket.onopen = function() {
        // chrome.storage.local.get(["username"], function(data) {
        //     websocket.send(JSON.stringify({userLoginId: data.username}));
        // });
        console.log('websocket connection open...')
    };

    websocket.onmessage = function (event) {
        try {
            console.log('receive message:'+event.data)
            var received_msg = JSON.parse(event.data);
            if(received_msg.type=="screen")
            {
                switch (received_msg.command) {
                    case "5":
                        currentUrlIndex++;
                        if(currentUrlIndex >= urlArray.length)
                        {
                            currentUrlIndex=0;
                        }
                        break;
                    case "1":
                        currentUrlIndex = 1;
                        break;
                    case "0":
                        currentUrlIndex = 0;
                        break;
                    default:
                        break;
                }
                chrome.tabs.query({},function(tabs){
                    console.log(tabs);
                    tabs.forEach(tab => {
                        let url = urlArray[currentUrlIndex];
                        if(tab.url == url)
                        {
                            chrome.tabs.update(tab.id,{active:true})
                        }
                    });
                })
            }
            //测试tab切换
            
        } catch (error) {
            console.log(error)
        }
    };

    //If the websocket is closed but the session is still active, create new connection again
    websocket.onclose = function() {
        websocket = undefined;
        if(autoReconnect)
        {
            createWebSocketConnection();
        }
    };
}

//Close the websocket connection
function closeWebSocketConnection() {
    if (websocket != null || websocket != undefined) {
        websocket.close();
        websocket = undefined;
    }
}